< previous page page_21 next page >

Page 21
Puzzle 5
Finding the Executable Name
You always know the name of your program. After all, you compiled it and probably installed it. But when you create software components, those components may be called from many different applications, and you won't necessarily know which application is using your component.
Why would you need to know this? The most common reason is if you want to license your component. You might want to detect whether it is being used from within the Visual Basic runtime environment or a compiled executable. If it's running within the VB environment, you can check to see if the license is present before allowing your component to run.
The Win32 API makes it easy to determine the name of the program that originally launched a process. The GetModuleFileName function does the trick. It is defined in the Win32 Software Development Kit (SDK) as follows:
DWORD GetModuleFileName(
    HMODULE hModule,    // handle to module to find filename for
    LPTSTR lpFilename,  // pointer to buffer to receive module path
    DWORD nSize // size of buffer, in characters
   );
Converting these parameter types to Visual Basic is so easy as to be almost routine. The hModule parameter is a handle, so it's a 32-bit Long value. The lpFilename parameter is a string that will be loaded with the full path and name of the executable. It will need to be declared ByVal as String. The nSize parameter is another 32-bit Long value that will contain the length of the string buffer. And, because the function deals with process management, it will be in the kernel32 dynamic link library. The function can thus be declared as follows:
Private Declare Function GetModuleFileName Lib "kernel32" Alias _
"GetModuleFileNameA" (ByVal hModule As Long, ByVal lpFileName As _
String, ByVal nSize As Long) As Long
The hModule parameter deserves further discussion. A module handle under Windows contains the address at which the given module is loaded in memory.

 
< previous page page_21 next page >